package cn.wj.school.cloud.exception;

import org.springframework.http.HttpStatus;

/**
 * @Author: yueding
 * @Description: 自定义异常类 实现SkipLogException 为了切面不记录日志 支持参数动态添加
 * @Date: Created in 15:27 2018/4/12
 * @Modified By: Copyright(c) cai-inc.com
 */
public class ServiceInvokeException extends RuntimeException {
    private static final long serialVersionUID = 2669040717172917220L;

    /**
     * 状态码
     */
    private HttpStatus code;

    private ServiceInvokeException() {}

    private ServiceInvokeException(HttpStatus code, String message) {
        super(message);
        if (code != null) {
            this.code = code;
        }
    }

    private ServiceInvokeException(HttpStatus code, String message, Throwable innerException) {
        super(message, innerException);
        this.code = code;
    }

    /**
     * 支持动态添加参数 加上http状态,区分错误类型
     * @param code http状态码
     * @param message
     * @param parameters
     * @return
     */
    public static ServiceInvokeException newException(HttpStatus code, String message, String... parameters) {
        return newException(code, null, message, parameters);
    }

    /**
     * 支持动态添加参数
     * 
     * @param message
     * @param parameters
     * @return
     */
    public static ServiceInvokeException newException(String message, String... parameters) {
        return newException(null, null, message, parameters);
    }

    public static ServiceInvokeException newException(HttpStatus status, Throwable innerException, String message,
            String... parameters) {
        StringBuilder result = new StringBuilder(message);
        if (parameters != null) {
            for (int i = 0; i < parameters.length; ++i) {
                String parameterName = "{" + i + "}";
                int indexFound = result.indexOf(parameterName);
                while (indexFound >= 0) {
                    result.replace(indexFound, indexFound + parameterName.length(), parameters[i]);
                    indexFound = result.indexOf(parameterName, indexFound);
                }
            }
        }
        if (innerException == null) {
            return new ServiceInvokeException(status, result.toString());
        } else {
            return new ServiceInvokeException(status, result.toString(), innerException);
        }

    }

    public static ServiceInvokeException newException(String message) {

        return new ServiceInvokeException(null, message);
    }

    public HttpStatus getCode() {
        return code;
    }
}
